#!/usr/bin/perl

use Cwd;
$current_directory = getcwd;
$default_directory = "/tmp";
#$default_directory = "/Users/arnoldyip/Desktop";

$user_path = shift;
$build1_path = shift;
$build2_path = shift;

chomp($user_path);
if ($user_path eq "") {
	die "User must provide the path of the Excel files."
}
chomp($build1_path);
if ($build1_path eq "") {
	die "User must provide the path of the Numbers build."
}
chomp($build2_path);
if ($build2_path eq "") {
	die "User must provide the path of the Numbers build."
}

#create directory numbers_excel_comparison_test in default directory if it does not exist
$hasTestFolder = 0;
chdir($default_directory);
@tmp_files = `ls`;
foreach $temp(@tmp_files) {
	chomp($temp);
	if ($temp eq 'numbers_excel_comparison_test') {
		$hasTestFolder = 1 if -d $temp;
	}
}
if (!$hasTestFolder) {
	mkdir("numbers_excel_comparison_test");
}

#determine test number and create a specific folder in the test directory
$test_num = 0;
chdir($default_directory."/numbers_excel_comparison_test");
@tmp_files = `ls`;
foreach $temp(@tmp_files) {
	chomp($temp);
	if ($temp > $test_num) {
		$test_num = $temp;
	}
}
$test_num ++;
mkdir($test_num);
$specific_test_folder = $default_directory."/numbers_excel_comparison_test/".$test_num;

#get a list of xls files in the specified folder
chdir $user_path;
@all_xls_files = `find $user_path -name "*.xls" -print`;
foreach (@all_xls_files) {
	#print;
}

#generate the error log files for each file and each build
chdir($current_directory);
print("Opening ".$build1_path."\n");
@args = ("osascript", "runLasso.scpt", $specific_test_folder, $build1_path, 1, @all_xls_files);
system(@args);
print("Opening ".$build2_path."\n");
@args = ("osascript", "runLasso.scpt", $specific_test_folder, $build2_path, 2, @all_xls_files);
system(@args);

#analyze the files created
print("Report listing errors created or fixed between 2 builds\n\n");

$total_num_saved = 0;
$total_num_broken = 0;
$fileCount = 1;
foreach $temp(@all_xls_files) {
	print("File ".$fileCount.": ".$temp);
	
	$num_saved = 0;
	$num_broken = 0;
	
	$file1_path = $default_directory."/numbers_excel_comparison_test/".$test_num."/".$fileCount."_build1";
	$file2_path = $default_directory."/numbers_excel_comparison_test/".$test_num."/".$fileCount."_build2";
	print $file1_path."\n";
	print $file2_path."\n";
		
	@diff_output = `diff -ua $file1_path $file2_path`;
	$line_count = 1;
	foreach $line(@diff_output) {
		$first_char = substr($line, 0, 1);
		#start at the third line, first 2 are just file names
		if($line_count>2) {
			if ($first_char eq '+') {
				print $line;
				$num_broken ++;
			}
			if ($first_char eq '-') {
				print $line;
				$num_saved ++;
			}
		}
		$line_count ++;
	}
	print("You fixed ".$num_saved." errors and created ".$num_broken." errors.\n\n");
	
	$total_num_saved += $num_saved;
	$total_num_broken += $num_broken;
	$fileCount ++;
}
print("For all files, you fixed ".$total_num_saved." errors and created ".$total_num_broken." errors.\n");
